{% extends "base.html" %}

{% block title %}修改评价 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}修改评价{% endblock %}

{% block extra_css %}
<style>
    .evaluation-form {
        max-width: 700px;
        margin: 0 auto;
        background: white;
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }

    .original-evaluation {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 30px;
        border-left: 4px solid #6c757d;
    }

    .original-evaluation h5 {
        color: #6c757d;
        margin-bottom: 15px;
    }

    .original-rating {
        display: flex;
        align-items: center;
        gap: 15px;
        margin: 15px 0;
    }

    .original-stars {
        font-size: 1.5rem;
        color: #ffc107;
    }

    .original-score {
        background: #6c757d;
        color: white;
        padding: 6px 10px;
        border-radius: 15px;
        font-weight: bold;
    }

    .original-comment {
        background: white;
        border-radius: 6px;
        padding: 15px;
        margin-top: 10px;
        font-style: italic;
        color: #555;
        border-left: 3px solid #6c757d;
    }

    .original-time {
        font-size: 0.9rem;
        color: #999;
        margin-top: 10px;
    }

    .edit-section {
        background: #fff5f5;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 25px;
        border-left: 4px solid #ff6b6b;
    }

    .edit-section h5 {
        color: #ff6b6b;
        margin-bottom: 20px;
    }

    .rating-section {
        margin: 25px 0;
        padding: 20px;
        background: #fff5f5;
        border-radius: 8px;
        border: 1px solid #ffebee;
    }

    .rating-stars {
        text-align: center;
        margin: 20px 0;
    }

    .rating-stars .star-option {
        display: inline-block;
        margin: 0 5px;
        padding: 12px 16px;
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        text-decoration: none;
        color: #333;
        min-width: 120px;
    }

    .rating-stars .star-option:hover {
        background: #fff3cd;
        border-color: #ffc107;
        transform: translateY(-2px);
        text-decoration: none;
        color: #333;
    }

    .rating-stars .star-option.selected {
        background: #ffc107;
        border-color: #ffc107;
        color: white;
        transform: translateY(-2px);
    }

    .star-display {
        font-size: 1.3rem;
        color: #ffc107;
        display: block;
        margin-bottom: 5px;
    }

    .rating-text {
        font-size: 0.85rem;
        font-weight: 500;
    }

    .selected .star-display {
        color: white;
    }

    .comment-section {
        margin: 25px 0;
    }

    .form-floating textarea {
        min-height: 120px;
    }

    .help-text {
        font-size: 0.875rem;
        color: #6c757d;
        margin-top: 5px;
    }

    .modification-notice {
        background: #d1ecf1;
        border: 1px solid #bee5eb;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 25px;
        border-left: 4px solid #17a2b8;
    }

    .modification-notice h6 {
        color: #0c5460;
        margin-bottom: 10px;
    }

    .modification-notice ul {
        margin-bottom: 0;
        color: #0c5460;
    }

    .btn-update {
        background: linear-gradient(135deg, #ffc107 0%, #ff8f00 100%);
        border: none;
        padding: 12px 30px;
        font-weight: 500;
        border-radius: 8px;
        color: white;
        transition: all 0.3s ease;
    }

    .btn-update:hover {
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(255,193,7,0.3);
    }

    .comparison-view {
        display: flex;
        gap: 20px;
        margin: 20px 0;
    }

    .comparison-side {
        flex: 1;
        padding: 15px;
        border-radius: 8px;
    }

    .comparison-side.before {
        background: #f8f9fa;
        border-left: 4px solid #6c757d;
    }

    .comparison-side.after {
        background: #fff5f5;
        border-left: 4px solid #ff6b6b;
    }

    .comparison-side h6 {
        margin-bottom: 15px;
        text-align: center;
    }

    .back-link {
        margin-bottom: 20px;
    }

    .time-limit-warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        border-left: 4px solid #ffc107;
    }

    .time-limit-warning h6 {
        color: #856404;
        margin-bottom: 10px;
    }

    .time-remaining {
        font-weight: bold;
        color: #dc3545;
    }

    @media (max-width: 768px) {
        .comparison-view {
            flex-direction: column;
        }

        .rating-stars .star-option {
            min-width: 80px;
            padding: 8px 10px;
            margin: 2px;
        }

        .star-display {
            font-size: 1.1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="back-link">
        <a href="{{ url_for('evaluations.detail', evaluation_id=evaluation.id) }}" class="btn btn-outline-secondary btn-sm">
            <i class="fas fa-arrow-left"></i> 返回评价详情
        </a>
    </div>

    <div class="evaluation-form">
        <!-- 修改时限提醒 -->
        <div class="time-limit-warning">
            <h6><i class="fas fa-clock"></i> 修改时限提醒</h6>
            <p class="mb-2">评价提交后24小时内可以修改，请及时完成修改。</p>
            {% if evaluation.student_submitted_at or evaluation.coach_submitted_at %}
                {% set submitted_time = evaluation.student_submitted_at if user_type == 'student' else evaluation.coach_submitted_at %}
                {% set hours_passed = ((moment.utcnow() - submitted_time).total_seconds() / 3600)|round(1) %}
                {% set hours_remaining = (24 - hours_passed)|round(1) %}
                <p class="mb-0">
                    已提交 <strong>{{ hours_passed }}</strong> 小时，
                    还可修改 <span class="time-remaining">{{ hours_remaining }}</span> 小时
                </p>
            {% endif %}
        </div>

        <!-- 修改说明 -->
        <div class="modification-notice">
            <h6><i class="fas fa-info-circle"></i> 修改说明</h6>
            <ul class="small">
                <li>您可以修改评分和评价内容</li>
                <li>修改后的评价将覆盖原有评价</li>
                <li>修改记录仅您本人可见</li>
                <li>请确保评价内容客观真实</li>
            </ul>
        </div>

        <!-- 原始评价显示 -->
        <div class="original-evaluation">
            <h5><i class="fas fa-history"></i> 当前评价</h5>

            {% if user_type == 'student' and evaluation.student_rating %}
                <div class="original-rating">
                    <div class="original-stars">
                        {% for i in range(evaluation.student_rating) %}★{% endfor %}
                        {% for i in range(5 - evaluation.student_rating) %}☆{% endfor %}
                    </div>
                    <div class="original-score">{{ evaluation.student_rating }}/5</div>
                    <div class="rating-text">
                        {% if evaluation.student_rating == 5 %}非常满意
                        {% elif evaluation.student_rating == 4 %}满意
                        {% elif evaluation.student_rating == 3 %}一般
                        {% elif evaluation.student_rating == 2 %}不满意
                        {% else %}很不满意{% endif %}
                    </div>
                </div>
                {% if evaluation.student_comment %}
                    <div class="original-comment">
                        "{{ evaluation.student_comment }}"
                    </div>
                {% endif %}
                {% if evaluation.student_submitted_at %}
                    <div class="original-time">
                        提交时间：{{ evaluation.student_submitted_at.strftime('%Y年%m月%d日 %H:%M') }}
                    </div>
                {% endif %}

            {% elif user_type == 'coach' and evaluation.coach_rating %}
                <div class="original-rating">
                    <div class="original-stars">
                        {% for i in range(evaluation.coach_rating) %}★{% endfor %}
                        {% for i in range(5 - evaluation.coach_rating) %}☆{% endfor %}
                    </div>
                    <div class="original-score">{{ evaluation.coach_rating }}/5</div>
                    <div class="rating-text">
                        {% if evaluation.coach_rating == 5 %}非常满意
                        {% elif evaluation.coach_rating == 4 %}满意
                        {% elif evaluation.coach_rating == 3 %}一般
                        {% elif evaluation.coach_rating == 2 %}不满意
                        {% else %}很不满意{% endif %}
                    </div>
                </div>
                {% if evaluation.coach_comment %}
                    <div class="original-comment">
                        "{{ evaluation.coach_comment }}"
                    </div>
                {% endif %}
                {% if evaluation.coach_submitted_at %}
                    <div class="original-time">
                        提交时间：{{ evaluation.coach_submitted_at.strftime('%Y年%m月%d日 %H:%M') }}
                    </div>
                {% endif %}
            {% endif %}
        </div>

        <!-- 修改表单 -->
        <div class="edit-section">
            <h5><i class="fas fa-edit"></i> 修改评价</h5>

            <form method="POST" novalidate>
                {{ form.hidden_tag() }}
                {{ form.evaluation_id() }}
                {{ form.evaluator_type() }}

                <!-- 评分修改 -->
                <div class="rating-section">
                    <label class="form-label">
                        <strong>
                            <i class="fas fa-star"></i> 重新评分
                        </strong>
                    </label>

                    <div class="rating-stars" id="rating-stars">
                        {% for value, label in form.rating.choices %}
                            <div class="star-option" data-value="{{ value }}"
                                 {% if form.rating.data == value %}class="selected"{% endif %}>
                                <span class="star-display">
                                    {% for i in range(value|int) %}★{% endfor %}
                                    {% for i in range(5 - value|int) %}☆{% endfor %}
                                </span>
                                <span class="rating-text">{{ label.split(' ', 1)[1] if ' ' in label else label }}</span>
                            </div>
                        {% endfor %}
                    </div>

                    {{ form.rating(style="display: none;") }}

                    {% if form.rating.errors %}
                        <div class="text-danger small">
                            {% for error in form.rating.errors %}
                                {{ error }}<br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- 评价内容修改 -->
                <div class="comment-section">
                    <div class="form-floating">
                        {{ form.comment(class="form-control", placeholder="请修改您的评价内容...") }}
                        {{ form.comment.label(class="form-label") }}
                    </div>
                    <div class="help-text">
                        您可以更详细地描述您的体验和建议
                    </div>
                    {% if form.comment.errors %}
                        <div class="text-danger small mt-2">
                            {% for error in form.comment.errors %}
                                {{ error }}<br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- 对比预览 -->
                <div class="comparison-view" id="comparison-preview" style="display: none;">
                    <div class="comparison-side before">
                        <h6>修改前</h6>
                        <div id="before-rating">-</div>
                        <div id="before-comment">-</div>
                    </div>
                    <div class="comparison-side after">
                        <h6>修改后</h6>
                        <div id="after-rating">-</div>
                        <div id="after-comment">-</div>
                    </div>
                </div>

                <!-- 提交按钮 -->
                <div class="text-center mt-4">
                    {{ form.submit(class="btn btn-update btn-lg me-3") }}
                    <a href="{{ url_for('evaluations.detail', evaluation_id=evaluation.id) }}"
                       class="btn btn-outline-secondary">取消修改</a>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 原始数据
    const originalData = {
        rating: {{ evaluation.student_rating if user_type == 'student' else evaluation.coach_rating }},
        comment: {{ (evaluation.student_comment if user_type == 'student' else evaluation.coach_comment)|tojson }}
    };

    // 评分选择交互
    $('.star-option').click(function() {
        var rating = $(this).data('value');

        // 更新隐藏的表单字段
        $('#rating').val(rating);

        // 更新视觉效果
        $('.star-option').removeClass('selected');
        $(this).addClass('selected');

        // 验证反馈
        $('#rating').removeClass('is-invalid');
        $('.rating-section .text-danger').hide();

        // 更新对比预览
        updateComparisonPreview();
    });

    // 评价内容变化监听
    $('#comment').on('input', function() {
        updateComparisonPreview();
        updateCharCount();
    });

    // 更新对比预览
    function updateComparisonPreview() {
        const newRating = $('#rating').val();
        const newComment = $('#comment').val();

        if (newRating || newComment !== originalData.comment) {
            $('#comparison-preview').show();

            // 更新修改前
            $('#before-rating').html(getStarDisplay(originalData.rating) + ' (' + originalData.rating + '/5)');
            $('#before-comment').text(originalData.comment || '无评价内容');

            // 更新修改后
            if (newRating) {
                $('#after-rating').html(getStarDisplay(newRating) + ' (' + newRating + '/5)');
            } else {
                $('#after-rating').text('-');
            }
            $('#after-comment').text(newComment || '无评价内容');
        } else {
            $('#comparison-preview').hide();
        }
    }

    // 生成星级显示
    function getStarDisplay(rating) {
        if (!rating) return '-';
        let stars = '';
        for (let i = 1; i <= 5; i++) {
            stars += i <= rating ? '★' : '☆';
        }
        return '<span style="color: #ffc107;">' + stars + '</span>';
    }

    // 字符计数
    function updateCharCount() {
        var length = $('#comment').val().length;
        var maxLength = 500;

        if (!$('.char-count').length) {
            $('#comment').after('<div class="char-count text-muted small mt-1"></div>');
        }

        $('.char-count').text(length + '/' + maxLength + ' 字符');

        if (length > maxLength) {
            $('.char-count').addClass('text-danger').removeClass('text-muted');
        } else {
            $('.char-count').addClass('text-muted').removeClass('text-danger');
        }
    }

    // 表单验证
    $('form').on('submit', function(e) {
        var isValid = true;

        // 验证评分
        if (!$('#rating').val()) {
            isValid = false;
            if (!$('.rating-section .text-danger').length) {
                $('.rating-section').append('<div class="text-danger small mt-2">请选择评分</div>');
            }
        }

        // 检查是否有修改
        const newRating = $('#rating').val();
        const newComment = $('#comment').val();

        if (newRating == originalData.rating && newComment === originalData.comment) {
            isValid = false;
            alert('您没有做任何修改，请修改评分或评价内容后再提交');
        }

        if (!isValid) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: $('.text-danger:first').offset().top - 100
            }, 500);
        } else {
            // 确认提交
            const confirmed = confirm('确定要提交修改吗？修改后的评价将覆盖原有评价。');
            if (!confirmed) {
                e.preventDefault();
            }
        }
    });

    // 初始化
    updateCharCount();

    // 自动保存修改草稿
    var draftKey = 'evaluation_edit_draft_{{ evaluation.id }}';

    // 加载草稿
    function loadDraft() {
        var draft = localStorage.getItem(draftKey);
        if (draft) {
            try {
                var draftData = JSON.parse(draft);
                if (draftData.timestamp && (Date.now() - draftData.timestamp) < 24 * 60 * 60 * 1000) {
                    if (draftData.comment && draftData.comment !== originalData.comment) {
                        $('#comment').val(draftData.comment);
                    }
                    if (draftData.rating && draftData.rating !== originalData.rating) {
                        $('#rating').val(draftData.rating);
                        $('.star-option[data-value="' + draftData.rating + '"]').addClass('selected');
                    }
                    updateComparisonPreview();
                    updateCharCount();
                }
            } catch (e) {
                console.log('加载草稿失败:', e);
            }
        }
    }

    // 保存草稿
    function saveDraft() {
        var draftData = {
            rating: $('#rating').val(),
            comment: $('#comment').val(),
            timestamp: Date.now()
        };
        localStorage.setItem(draftKey, JSON.stringify(draftData));
    }

    // 清除草稿
    function clearDraft() {
        localStorage.removeItem(draftKey);
    }

    // 监听输入变化保存草稿
    $('#comment, #rating').on('change input', function() {
        saveDraft();
    });

    // 提交成功后清除草稿
    $('form').on('submit', function() {
        if ($('#rating').val()) {
            clearDraft();
        }
    });

    // 页面加载时加载草稿
    loadDraft();

    // 离开页面确认
    window.addEventListener('beforeunload', function(e) {
        const newRating = $('#rating').val();
        const newComment = $('#comment').val();

        if ((newRating && newRating != originalData.rating) ||
            (newComment !== originalData.comment)) {
            e.preventDefault();
            e.returnValue = '您有未保存的修改，确定要离开吗？';
        }
    });
});
</script>
{% endblock %}